var net = require('net');

var HOST = '127.0.0.1';
var PORT = 8085;

var socket = net.createServer();
socket.listen(PORT, HOST);
console.log('Server listening on ' + HOST +':'+ PORT);

//监听链接
socket.on("connection",onConnection);

function onConnection(sock) {

    // 我们获得一个连接 - 该连接自动关联一个socket对象
    console.log('CONNECTED: ' +
        sock.remoteAddress + ':' + sock.remotePort);

    // 为这个socket实例添加一个"data"事件处理函数
    sock.on('data', request.bind(null,sock));

    // 为这个socket实例添加一个"close"事件处理函数
    sock.on('close', function(data) {
        console.log('CLOSED: ' +
            sock.remoteAddress + ' ' + sock.remotePort);
    });

    sock.on("error",function(error){
        console.log('ERROR:' +
            error);
        //sock.close();
    })

}

function request(sock,req){
        // console.log(data)
        console.log('request FROM ' + sock.remoteAddress + ': ' + sock.remotePort);
        console.log("request :"+ req);

        //解析消息
        var msg = {};
        msg.magicCode = req.slice(0,4);
        msg.typeCode = req.slice(4,8);
        msg.size = parseInt(req.slice(8,12));
        msg.bodyData = req.slice(12,12+size);

        console.log('msg: '+ msg);

        var response = {};
        response.magicCode = new Buffer(4);
        response.magicCode.write("\0RES");
        response.typeCode = new Buffer(4);
        response.typeCode.write("17");//17=>ECHO_RES
        response.size = new Buffer(4);
        response.bodyData = new Buffer(msg.bodyData.toString().toUpper());

    var clientRequest = Buffer.concat(
    [response.magicCode,
    response.typeCode,
    response.size,
    response.bodyData]
    );
    console.log("response : "+clientRequest);
        // 回发该数据，客户端将收到来自服务端的数据
        sock.write(clientRequest);
    }

